package ue

import (
	"cybertwin/utils/protocol"
	"fmt"
	"sync"

	"github.com/panjf2000/gnet/v2"
	log "github.com/sirupsen/logrus"
)

const (
	AP_IP string = "127.0.0.1"
	// CT_PORT = "30202"
	Ap_PORT string = "8082"
)

type RegistryClient struct {
	gnet.BuiltinEventEngine
	eng      gnet.Engine
	MacAddr  string
	Username string
	Uid      string
	Ueid     string
	Ctid     string
	Hid      string
	shutdown bool
	Finish   bool
	// uePrivateKey      *rsa.PrivateKey // 设备自身的密钥对
	// registryPublicKey *rsa.PublicKey
	Wg      *sync.WaitGroup
	Ap_IP   string
	Ap_port string
}

func (client *RegistryClient) OnBoot(eng gnet.Engine) (action gnet.Action) {
	log.Infoln("[OnBoot]-registry client starting")
	client.eng = eng
	client.shutdown = false
	client.Finish = false
	// client.uePrivateKey = cryptotools.RSA_LoadPrivateKey("./ca/ue", "ue_sk_1.pem")
	return
}

func (client *RegistryClient) OnOpen(conn gnet.Conn) (out []byte, action gnet.Action) {
	// 连接开启后，直接发送register user和 ue请求
	err := client.RegisterUser(conn)
	if err != nil {
		log.Warnln("[RegistryClient OnOpen]-RegistryUser failed")
		action = gnet.Close
	}
	fmt.Println("-----------------------")
	return
}

func (client *RegistryClient) OnTraffic(conn gnet.Conn) (action gnet.Action) {
	data, typeName, _, err := protocol.CodecUtils.AccessProtocolCodec.Decode(conn)
	if err != nil {
		log.Errorln("[Register-", typeName, "]-读取注册消息失败", err.Error())
		action = gnet.None
		return
	}
	switch typeName {
	case protocol.TYPE_USER_RESPONSE.GetName():
		err := client.handler_USER_RESPONSE(data, conn)
		if err != nil {
			log.Errorln("[RegistryClient OnTraffic]-[TYPE_USER_RESPONSE]-", err.Error())
		}
		log.Infoln("[RegistryClient OnTraffic]-User注册完成-starting to register ue ")
		fmt.Println("-----------------------")

	case protocol.TYPE_RESPONSE.GetName():
		err := client.handler_RESPONSE(data)
		if err != nil {
			log.Errorln("[RegistryClient OnTraffic]-[TYPE_RESPONSE]-", err.Error())
		}
		log.Infoln("[RegistryClient OnTraffic]-Ue注册完成-starting to access")
		fmt.Println("-----------------------")
		client.Ap_IP, client.Ap_port = AP_IP, Ap_PORT
		client.Wg.Done()
	}
	return
}
